package gold.digger;

import gold.utils.InputUtil;
import gold.utils.UF;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC1361 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {

        /**
         * Created by fanzhenyu02 on 2020/6/27.
         * Union Find 算法实现
         */
        public class UF {
            // 连通分量个数
            private int count;
            // 存储一棵树
            private int[] parent;
            // 记录树的“重量”
            private int[] size;

            public UF(int n) {
                this.count = n;
                parent = new int[n];
                size = new int[n];
                for (int i = 0; i < n; i++) {
                    parent[i] = i;
                    size[i] = 1;
                }
            }

            /* 将 p 和 q 连接 */
            public void union(int p, int q) {
                int rootP = find(p);
                int rootQ = find(q);
                if (rootP == rootQ)
                    return;

                // 小树接到大树下面，较平衡
                if (size[rootP] > size[rootQ]) {
                    parent[rootQ] = rootP;
                    size[rootP] += size[rootQ];
                } else {
                    parent[rootP] = rootQ;
                    size[rootQ] += size[rootP];
                }
                count--;
            }

            /* 判断 p 和 q 是否连通 */
            public boolean connected(int p, int q) {
                int rootP = find(p);
                int rootQ = find(q);
                return rootP == rootQ;
            }

            private int find(int x) {
                while (parent[x] != x) {
                    // 进行路径压缩
                    parent[x] = parent[parent[x]];
                    x = parent[x];
                }
                return x;
            }

            /* 返回图中有多少个连通分量 */
            public int count() {
                return count;
            }

            /* 返回图中联通集合 */
            public Map<Integer, List<Integer>> outputAggregateSet(int n) {
                Map<Integer, List<Integer>> aggregateMap = new HashMap<>();

                // 共有n个集合
                for (int i = 0; i < n; i++) {
                    int parentId = find(i);
                    if (!aggregateMap.containsKey(parentId)) aggregateMap.put(parentId, new ArrayList<>());
                    aggregateMap.get(parentId).add(i);
                }

                System.out.println(aggregateMap.toString());
                return aggregateMap;
            }
        }

        public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) {
            UF uf = new UF(n);
            int[] parent = new int[n];
            Arrays.fill(parent, -1);

            for (int i = 0; i < n; i++) {
                if (-1 == leftChild[i]) continue;
                if (uf.connected(i, leftChild[i])) return false;
                uf.union(i, leftChild[i]);

                if (parent[leftChild[i]] != -1) {
                    // 当前 leftChild[i] 已经有parent
                    if (parent[leftChild[i]] != i) return false;
                } else {
                    parent[leftChild[i]] = i;
                }
            }

            for (int i = 0; i < n; i++) {
                if (-1 == rightChild[i]) continue;
                if (uf.connected(i, rightChild[i])) return false;
                uf.union(i, rightChild[i]);

                if (parent[rightChild[i]] != -1) {
                    // 当前 rightChild[i] 已经有parent
                    if (parent[rightChild[i]] != i) return false;
                } else {
                    parent[rightChild[i]] = i;
                }
            }

            return uf.count == 1;
        }
    }

    public void run() {
        Solution solution = new Solution();

//        输入：n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]
//        输出：true
//        int[] leftChild = InputUtil.toIntegerArray("[1,-1,3,-1]");
//        int[] rightChild = InputUtil.toIntegerArray("[2,-1,-1,-1]");
//        System.out.println(solution.validateBinaryTreeNodes(4, leftChild, rightChild));

//        输入：n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]
//        输出：false
//        int[] leftChild = InputUtil.toIntegerArray("[1,-1,3,-1]");
//        int[] rightChild = InputUtil.toIntegerArray("[2,3,-1,-1]");
//        System.out.println(solution.validateBinaryTreeNodes(4, leftChild, rightChild));

//        输入：n = 2, leftChild = [1,0], rightChild = [-1,-1]
//        输出：false
//        int[] leftChild = InputUtil.toIntegerArray("[1,0]");
//        int[] rightChild = InputUtil.toIntegerArray("[-1,-1]");
//        System.out.println(solution.validateBinaryTreeNodes(2, leftChild, rightChild));

//        输入：n = 6, leftChild = [1,-1,-1,4,-1,-1], rightChild = [2,-1,-1,5,-1,-1]
//        输出：false
        int[] leftChild = InputUtil.toIntegerArray("[1,-1,-1,4,-1,-1]");
        int[] rightChild = InputUtil.toIntegerArray("[2,-1,-1,5,-1,-1]");
        System.out.println(solution.validateBinaryTreeNodes(6, leftChild, rightChild));

    }

    public static void main(String[] args) throws Exception {
        LC1361 an = new LC1361();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
